package message;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.common.model.FdMessage;
import com.demo.common.model.FdRoomUser;
import com.jfinal.json.Json;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zhenyi.common.model.TgUser;

import cn.hutool.core.lang.Singleton;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	// ChannelGroup allChannels = new DefaultChannelGroup("ChannelGroups",
	// GlobalEventExecutor.INSTANCE);
	ChannelGroup allChannels = Singleton.get(WSServer.class).allChannels;
	protected WSServer server = Singleton.get(WSServer.class);

	/**
	 * 在线
	 */
	protected final int ISUSERIN_YES = 1;
	/**
	 * 下线
	 */
	protected final int ISUSERIN_NO = 0;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		JSONObject jsStr = JSONObject.parseObject(msg.text());
		String uid = jsStr.getString("uid");
		if (!StrKit.isBlank(uid)) {
			Kv cond = Kv.by("userCode", uid);
			cond.set("roomCode",jsStr.getString("roomCode"));
			SqlPara sqlPara = Db.use("demo").getSqlPara("findUserByUserCode", cond);
			List<Record> list = Db.use("demo").find(sqlPara);
			for (Record record : list) {
				FdRoomUser fdRoomUser = FdRoomUser.dao.findById(record.getLong("id"));
				fdRoomUser.setUid(ctx.channel().id().asLongText());
				fdRoomUser.setIsUserIn(ISUSERIN_YES);//设置上线
				fdRoomUser.update();
			}
		} else {
			SenderMessage(jsStr);// 群聊
			// ctx.channel().writeAndFlush(new TextWebSocketFrame("cnt"));

			// System.out.println("read0");
			// System.out.println(channel.remoteAddress() + ": " + msg.text());

			// if ("123".equals(msg.text())) {
			// ctx.close();
			// return;
			// }
		}
	}

	/**
	 * 群聊
	 * 
	 * @param jsStr
	 */
	protected void SenderMessage(JSONObject jsStr) {
		Kv cond = Kv.by("roomCode", jsStr.getString("roomCode"));
		SqlPara sqlPara = Db.use("demo").getSqlPara("findRoomUser", cond);
		List<Record> list = Db.use("demo").find(sqlPara);
		String userCode = jsStr.getString("userCode");
		Long fromUserId = null;
		for (Record record : list) {
			if (userCode.equals(record.getStr("userCode"))) {
				fromUserId = record.getLong("userId");
			}
		}
		FdMessage fdMessage = new FdMessage();
		fdMessage.setFromUserId(fromUserId);
		fdMessage.setToUserId(list.get(0).getLong("roomId"));
		fdMessage.setContent(jsStr.getString("content"));
		fdMessage.setRoomId(list.get(0).getLong("roomId"));
		fdMessage.setAddTime();
		fdMessage.save();
		TgUser fromUser = TgUser.dao.findById(fromUserId);
		for (Record record : list) {
			if (record.getInt("isUserIn") == 1) {//在线才发送
				JSONObject json = new JSONObject();
				json.put("content", fdMessage.getContent());
				json.put("name", fromUser.getName());
				json.put("logo", fromUser.getLogo());
				String time = FdMessage.dao.findById(fdMessage.getId()).getAddTime().toString();
				json.put("time", time);
				server.send(json.toJSONString(), record.getStr("uid"));
			}
		}
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		System.out.println("连接" + ctx.channel().id().asLongText());
		allChannels.add(ctx.channel());
		// int size = allChannels.size();
		ctx.channel().writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asLongText()));
		// allChannels.writeAndFlush(new TextWebSocketFrame(size + "来自服务端: "));
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Kv cond = Kv.by("uid", ctx.channel().id().asLongText());
		SqlPara sqlPara = Db.use("demo").getSqlPara("findFdRoomUserByUid", cond);
		List<Record> list = Db.use("demo").find(sqlPara);
		for (Record record : list) {
			FdRoomUser fdRoomUser = FdRoomUser.dao.findById(record.getLong("id"));
			fdRoomUser.setIsUserIn(ISUSERIN_NO);//设置下线
			fdRoomUser.update();
		}
		System.out.println("用户下线: " + ctx.channel().id().asLongText());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}
}